package com.junmeng.libfloating.tab

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.View
import com.junmeng.libfloating.*
import com.junmeng.libfloating.ball.IPanelTab
import com.junmeng.libfloating.base.FloatingManager
import com.junmeng.libfloating.widget.LogRecyclerView

class TabLog : IPanelTab {
    companion object {
        const val FLOATING_KEY_LOG = "floating_key_log"
        const val FLOATING_KEY_LOG_LEVEL = "floating_key_log_level"
        const val FLOATING_ACTION_LOG = "action.floating.log.post"
    }

    private var logView: LogRecyclerView? = null
    private lateinit var clearView: View
    private lateinit var scrollToBottomView: View
    private var myReceiver: MyReceiver
    private var cache = arrayListOf<LogRecyclerView.LogContent>()

    init {
        myReceiver = MyReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(FLOATING_ACTION_LOG)
        FloatingManager.application?.registerReceiver(myReceiver, intentFilter)
    }

    override fun getLayoutResId(): Int {
        return R.layout.floating_tab_log
    }

    override fun getLabel(): String {
        return "日志"
    }

    override fun onInitView(view: View) {

        logView = view.findViewById(R.id.floating_log)
        clearView = view.findViewById(R.id.clear)
        scrollToBottomView = view.findViewById(R.id.scroll_to_bottom)
        clearView.setOnClickListener {
            logView?.clearLog()
        }
        scrollToBottomView.setOnClickListener {
            logView?.smoothScrollToEnd()
        }

        appendLogContents(cache)
        cache.clear()
    }

    fun appendLogContents(logContents: List<LogRecyclerView.LogContent>) {
        logView?.appendLogs(logContents)
    }


    inner class MyReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val log = intent.getStringExtra(FLOATING_KEY_LOG)
            val logLevel =
                intent.getIntExtra(FLOATING_KEY_LOG_LEVEL, LogRecyclerView.LogType.DEFAULT)
            log?.let {
                var logContent = LogRecyclerView.LogContent(log = log, level = logLevel)
                if (logView == null) {
                    cache.add(logContent)
                } else {
                    cache.add(logContent)
                    appendLogContents(cache)
                    cache.clear()
                }
            }
        }
    }

}